package com.evendai.sipdemo.sip.helper

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Handler
import android.os.Looper
import com.evendai.loglibrary.Timber
import com.evendai.sipdemo.App
import com.evendai.sipdemo.sip.NativeService
import org.doubango.ngn.NgnEngine
import kotlin.concurrent.thread

/** Engine帮助类 */
object EngineHelper: BroadcastReceiver() {

    private var callback: ((Boolean) -> Unit?)? = null

    /** 启动Engine */
    fun startEngine(callback: (Boolean) -> Unit?) {
        Timber.fi("开始启动Engine")
        EngineHelper.callback = callback
        App.getContext().registerReceiver(this, IntentFilter(NativeService.ACTION_ENGINE_STARTED))

        NgnEngine.getInstance().nativeServiceClass = NativeService::class.java

        if (NgnEngine.getInstance().isStarted) {
            Timber.fi("Engine本来就启动好了")
            callback(true)
            release()
        } else {
            thread(priority = Thread.MAX_PRIORITY) {
                // 没有网络也能开启成功，开启成功后会发送一个NativeService.ACTION_ENGINE_STARTED
                // 这个start()方法执行需要200毫秒左右，虽然不开子线程也没事，但是里面有读文件操作，如果文件大了时间就会变长，所以最好开子线程来完成
                val startSuccess = NgnEngine.getInstance().start()
                Timber.fi("engine.start()函数返回结果：$startSuccess")
                if (!startSuccess) {
                    Timber.fw("Engine启动失败，engine.start()函数返回false")
                    Handler(Looper.getMainLooper()).post { callback(false) }
                    release()
                }
            }
        }
    }

    /** 停止Engine */
    fun stopEngine(callback: () -> Unit?) {
        thread {
            if (NgnEngine.getInstance().isStarted) {
                val stopSuccess = NgnEngine.getInstance().stop()
                Timber.fi("Engine停止函数调用结果：$stopSuccess")
            }
            Handler(Looper.getMainLooper()).post { callback() }
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        Timber.fi("Engine启动成功")
        callback?.invoke(true)
        release()
    }

    private fun release() {
        if (callback != null) {
            App.getContext().unregisterReceiver(this)
        }
        callback = null
    }

}